package com.eventur;


import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView.ScaleType;

public class MainActivity extends Activity {
	/** Called when the activity is first created. */

	ListEvents listEvent = new ListEvents();

	static final int DATE_DIALOG_ID = 0;
	static int mYear = 0;
	static int mMonth=0;
	static int mDay=0;
	private static String selectedDate="";


	private static final int MENU_HOME = Menu.FIRST;
	private static final int MENU_BROWSE = Menu.FIRST+1;
	private static final int MENU_SEARCH = Menu.FIRST+2;
	private static final int MENU_QUIT = Menu.FIRST+3;
	XmlParser xmlParser = null;
	URL url = null;
	private static String tag = "MainActivity";


	private Bundle bundle = new Bundle();
	private static String category = "";
	ListView l1;
	private static String[] categoryType={"Type","Map","Organization","Venue","My Location","Date"};
	static String selectedCategoryType ="Type";


	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	protected void onResume(){
		super.onResume();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		// Add two example menu buttons
		menu.add(0,MENU_HOME,0,"Home");
		menu.add(0,MENU_BROWSE,1,"Browse");
		menu.add(0,MENU_SEARCH,2,"Search");
		menu.add(0,MENU_QUIT,4,"Quit");
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()	){
		case MENU_HOME: 
			return true;
		case MENU_BROWSE: getChoice();
		return true;
		case MENU_SEARCH: searchEvent();
		return true;
		case MENU_QUIT: int pid = android.os.Process.myPid();
		android.os.Process.killProcess(pid); finish();
		return true;

		}
		return false;

	}


	private void searchEvent() {

		LayoutInflater factory = LayoutInflater.from(MainActivity.this);
		final View textEntryView = factory.inflate(R.layout.search, null);
		final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
		alert.setIcon(R.drawable.icon);
		alert.setTitle("Search Event Based On");
		alert.setView(textEntryView);
		final RadioButton titlerb =(RadioButton)textEntryView.findViewById(R.id.title);
		final RadioButton typerb =(RadioButton)textEntryView.findViewById(R.id.type);
		final RadioButton orgrb =(RadioButton)textEntryView.findViewById(R.id.org);
		final RadioButton venuerb =(RadioButton)textEntryView.findViewById(R.id.venue);
		final EditText searchText = (EditText) textEntryView.findViewById(R.id.searchtext);
		alert.setPositiveButton("Search", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int whichButton) {
				String attribute="";String searchValue = null;
				if(titlerb.isChecked()==true){
					attribute = "title";
				}
				if(typerb.isChecked()==true){
					attribute = "type";
				}
				if(orgrb.isChecked()==true){
					attribute = "org";
				}
				if(venuerb.isChecked()==true){
					attribute = "venue";
				}



				try{
					searchValue = searchText.getText().toString();

					if(searchValue.length()<2){
						final AlertDialog.Builder wrongAddressAlert = new AlertDialog.Builder(MainActivity.this);
						wrongAddressAlert.setTitle("Type In Some Text To Search For");
						wrongAddressAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichButton) {
								searchEvent();
							}
						});
						wrongAddressAlert.show();

					}
					else{
						System.out.println("search value:"+searchValue);
						Intent intent = new Intent(MainActivity.this, ListViewActivity.class);
						bundle.putString("category", "search");
						bundle.putString("attribute", attribute);
						bundle.putString("searchValue", searchValue);
						intent.putExtras(bundle);
						startActivity(intent);
					}
				}
				catch(Exception e){
					final AlertDialog.Builder wrongAddressAlert = new AlertDialog.Builder(MainActivity.this);
					wrongAddressAlert.setTitle("Type In Some Text To Search For");
					wrongAddressAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							searchEvent();
						}
					});
					wrongAddressAlert.show();



				}
				Toast.makeText(getApplicationContext(), "Search based on type : "+attribute+" for "+searchValue, Toast.LENGTH_SHORT).show();

			}


		});
		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.cancel();
			}
		});
		alert.show();



	}
	private void getChoice() {

		final AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setIcon(R.drawable.category);
		alt_bld.setTitle("Categories");
		alt_bld.setSingleChoiceItems(categoryType, -1, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				System.out.println("Category selected= "+categoryType[item]);
				Toast.makeText(getApplicationContext(), "Category selected : "+categoryType[item], Toast.LENGTH_SHORT).show();
				category=categoryType[item];


				if(category.equalsIgnoreCase("Date")){
					showDialog(DATE_DIALOG_ID);

				}
				else if(category.equalsIgnoreCase("Map")){
					AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
					alertDialog.setTitle("Map");
					alertDialog.setIcon(R.drawable.gpsandroid);
					alertDialog.setMessage("Allow device to fetch your current Location?");
					//alertDialog.setIcon(R.drawable.search);
					alertDialog.setButton("Fetch", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(MainActivity.this, ListViewActivity.class);
							bundle.putString("category", category);
							intent.putExtras(bundle);
							startActivity(intent);
						}

					});
					alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							return;
						}}); 
					alertDialog.show();
				}
				else if(category.equalsIgnoreCase("My Location")){

					AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
					alertDialog.setTitle("Your Location");
					alertDialog.setIcon(R.drawable.gpsandroid);
					alertDialog.setMessage("Allow device to fetch your current Location?");
					//alertDialog.setIcon(R.drawable.search);
					alertDialog.setButton("Fetch", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(MainActivity.this, ListViewActivity.class);
							bundle.putString("category", category);
							intent.putExtras(bundle);
							startActivity(intent);
						}

					});
					alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							return;
						}}); 
					alertDialog.show();
				}
				else{
					final String itemList[];
					itemList = listEvent.getList(category);


					AlertDialog.Builder alertInside = new AlertDialog.Builder(MainActivity.this);
					alertInside.setIcon(R.drawable.category);
					alertInside.setTitle(category);
					alertInside.setSingleChoiceItems(itemList, -1, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int item) {


							Intent intent = new Intent(MainActivity.this, ListViewActivity.class);
							bundle.putString("category", category);
							bundle.putString("attribute", itemList[item]);
							intent.putExtras(bundle);
							startActivity(intent);

							Toast.makeText(getApplicationContext(), category+" category and " +itemList[item]+ " type selected", Toast.LENGTH_SHORT).show();

						}
					});
					AlertDialog alert = alertInside.create();
					alert.show();
				}
			}
		});
		AlertDialog alert = alt_bld.create();
		alert.show();

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this,
					mDateSetListener,
					mYear, mMonth, mDay);
		}
		return null;
	}	


	private DatePickerDialog.OnDateSetListener mDateSetListener =
		new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year,
				int monthOfYear, int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear +1;
			mDay = dayOfMonth;
			selectedDate = Integer.toString(mMonth)+"-"+Integer.toString(mDay)+"-"+Integer.toString(mYear);
			Intent intent = new Intent(MainActivity.this, ListViewActivity.class);
			bundle.putString("category", category);
			bundle.putString("attribute", selectedDate);
			intent.putExtras(bundle);
			startActivity(intent);
			System.out.println("selected date is:"+selectedDate);
		}
	};

	public boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnectedOrConnecting()) {
			return true;
		}
		return false;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.homescreen);

		final Calendar cal = Calendar.getInstance();
		mYear = cal.get(Calendar.YEAR);
		mMonth = cal.get(Calendar.MONTH);
		mDay = cal.get(Calendar.DAY_OF_MONTH);

		if(!isOnline()){
			AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
			alertDialog.setTitle("Need Internet Connection");
			alertDialog.setIcon(R.drawable.icon);
			alertDialog.setMessage("This application needs a working internet connection?");
			//alertDialog.setIcon(R.drawable.search);
			alertDialog.setButton2("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					return;
				}}); 
			alertDialog.show();

		}
		try {
			url = new URL("http://eventur.sis.pitt.edu/home.rss");
			xmlParser = new XmlParser(url.openStream());

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int increment =0;
		increment = xmlParser.buildParser();
		System.out.println(increment);
		if(increment==1){
			try{
				for(int i=0;i<=XmlParser.eventsNodeList.getLength()-1;i++){
					increment = xmlParser.parseEvents(i);
				}
			}
			catch(Exception e){
				e.printStackTrace();
			}
		}

		l1 = (ListView) findViewById(R.id.ListView01);

		Button todayButton = (Button) findViewById(R.id.todayButton);
		todayButton.setOnClickListener(new View.OnClickListener() {
			String [] eventTitleArray = new String[XmlParser.todayEvents.size()];
			String [] eventDateArray = new String[XmlParser.todayEvents.size()];
			String [] eventImageLinkArray = new String[XmlParser.todayEvents.size()];

			public void onClick(View v) {
				Event event = new Event();
				System.out.println("today button clicked");
				for(int i=0;i<XmlParser.todayEvents.size();i++){
					event = XmlParser.todayEvents.get(i);
					System.out.println("tomo event name:"+event.getTitle());
					eventTitleArray[i] = event.getTitle();
					if(event.getDistance()!=0.0)
						eventDateArray[i] = event.getsDate() +" - " +Double.toString(event.getDistance())+"mi";
					else
						eventDateArray[i] = event.getsDate();					
					eventImageLinkArray[i] = event.getImageLink();

					Log.i(tag , "today event detail"+event.getTitle());
				}
				l1.setAdapter(new EfficientAdapter(MainActivity.this,eventTitleArray,eventDateArray,eventImageLinkArray));
				l1.setFocusable(false);
				l1.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
						Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
						Bundle b = new Bundle();
						System.out.println("position in list:"+position);
						System.out.println("title name in the list:"+eventTitleArray[position]);
						b.putString("eventTitle", eventTitleArray[position]);
						intent.putExtras(b);
						startActivity(intent);

						Toast.makeText(getApplicationContext(), "Detailed view for the Event", Toast.LENGTH_SHORT).show();


					}
				});



			}
		});

		Button tomorrowButton = (Button) findViewById(R.id.tomorrowButton);
		tomorrowButton.setOnClickListener(new View.OnClickListener() {
			String [] eventTitleArray = new String[XmlParser.tomorrowEvents.size()];
			String [] eventDateArray = new String[XmlParser.tomorrowEvents.size()];
			String [] eventImageLinkArray = new String[XmlParser.tomorrowEvents.size()];

			public void onClick(View v) {
				Event event = new Event();
				System.out.println("Tomorrow button clicked");
				for(int i=0;i<XmlParser.tomorrowEvents.size();i++){
					event = XmlParser.tomorrowEvents.get(i);
					eventTitleArray[i] = event.getTitle();
					if(event.getDistance()!=0.0)
						eventDateArray[i] = event.getsDate() +" - " +Double.toString(event.getDistance())+"mi";
					else
						eventDateArray[i] = event.getsDate();					
					eventImageLinkArray[i] = event.getImageLink();

					System.out.println("tomo event name:"+event.getTitle());
				}
				l1.setAdapter(new EfficientAdapter(MainActivity.this,eventTitleArray,eventDateArray,eventImageLinkArray));
				l1.setFocusable(false);
				l1.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
						Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
						Bundle b = new Bundle();
						System.out.println("position in list:"+position);
						System.out.println("title name in the list:"+eventTitleArray[position]);
						b.putString("eventTitle", eventTitleArray[position]);
						intent.putExtras(b);
						startActivity(intent);

						Toast.makeText(getApplicationContext(), "Detailed view for the Event", Toast.LENGTH_SHORT).show();


					}
				});


			}
		});

		Button weekButton = (Button) findViewById(R.id.WeekButton);
		weekButton.setOnClickListener(new View.OnClickListener() {
			String [] eventTitleArray = new String[XmlParser.weekEvents.size()];
			String [] eventDateArray = new String[XmlParser.weekEvents.size()];
			String [] eventImageLinkArray = new String[XmlParser.weekEvents.size()];

			public void onClick(View v) {
				Event event = new Event();
				System.out.println("week button button clicked");
				for(int i=0;i<XmlParser.weekEvents.size();i++){
					event = XmlParser.weekEvents.get(i);
					eventTitleArray[i] = event.getTitle();
					if(event.getDistance()!=0.0)
						eventDateArray[i] = event.getsDate() +" - " +Double.toString(event.getDistance())+"mi";
					else
						eventDateArray[i] = event.getsDate();					
					eventImageLinkArray[i] = event.getImageLink();

					System.out.println("week event name:"+event.getTitle());
				}
				l1.setAdapter(new EfficientAdapter(MainActivity.this,eventTitleArray,eventDateArray,eventImageLinkArray));
				l1.setFocusable(false);
				l1.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
						Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
						Bundle b = new Bundle();
						System.out.println("position in list:"+position);
						System.out.println("title name in the list:"+eventTitleArray[position]);
						b.putString("eventTitle", eventTitleArray[position]);
						intent.putExtras(b);
						startActivity(intent);

						Toast.makeText(getApplicationContext(), "Detailed view for the Event", Toast.LENGTH_SHORT).show();


					}
				});
			}
		});


		try{
			Event event = new Event();
			final String [] eventTitleArray = new String[XmlParser.todayEvents.size()];
			String [] eventDateArray = new String[XmlParser.todayEvents.size()];
			String [] eventImageLinkArray = new String[XmlParser.todayEvents.size()];

			//System.out.println("Processing today list");
			System.out.println("Size of total list:"+XmlParser.eventsList.size());
			System.out.println("Size of today list:"+XmlParser.todayEvents.size());
			System.out.println("Size of tomorrow List:"+XmlParser.tomorrowEvents.size());
			System.out.println("Size of week list:"+XmlParser.weekEvents.size());
			for(int i=0;i<XmlParser.todayEvents.size();i++){
				event = XmlParser.todayEvents.get(i);
				eventTitleArray[i] = event.getTitle();
				if(event.getDistance()!=0.0)
					eventDateArray[i] = event.getsDate() +" - " +Double.toString(event.getDistance())+"mi";
				else
					eventDateArray[i] = event.getsDate();
				eventImageLinkArray[i] = event.getImageLink();


				Log.i(tag , "event detail"+event.getTitle());
			}
			l1.setAdapter(new EfficientAdapter(MainActivity.this,eventTitleArray,eventDateArray,eventImageLinkArray));
			//l1 = getListView();
			l1.setFocusable(false);
			l1.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int position, long arg3) {
					Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
					Bundle b = new Bundle();
					System.out.println("position in list:"+position);
					System.out.println("title name in the list:"+eventTitleArray[position]);
					b.putString("eventTitle", eventTitleArray[position]);
					intent.putExtras(b);
					startActivity(intent);

					Toast.makeText(getApplicationContext(), "Detailed view for the Event", Toast.LENGTH_SHORT).show();


				}
			});
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}


	private class EfficientAdapter extends BaseAdapter{
		private LayoutInflater mInflater;

		private String eventTitleArray[];
		private String eventDateArray[];
		private String eventImageLinkArray[];


		public EfficientAdapter(Context context,String[] eventTitleArray,String[] eventDateArray, String[] eventImageLinkArray){
			mInflater = LayoutInflater.from(context);

			this.eventDateArray=eventDateArray;
			this.eventTitleArray=eventTitleArray;
			this.eventImageLinkArray =eventImageLinkArray;

		}
		public int getCount(){
			//return XmlParser.todayEvents.size()-1;
			return this.eventDateArray.length;
		}
		public Object getItem(int position){
			return position;
		}
		public long getItemId(int position){
			return position;
		}
		public View getView(int position, View convertView, ViewGroup parent){
			ViewHolder holder;
			if(convertView == null){
				convertView = mInflater.inflate(R.layout.listview,null);
				holder = new ViewHolder();
				holder.firstLine = (TextView) convertView.findViewById(R.id.firstLineView);
				holder.secondLine = (TextView) convertView.findViewById(R.id.secondLineView);
				holder.imageView = (ImageView) convertView.findViewById(R.id.linkImage);
				//holder.checkbox = (CheckBox) convertView.findViewById(R.id.star);
				holder.firstLine.setFocusable(false);
				holder.secondLine.setFocusable(false);
				holder.imageView.setFocusable(false);
				//holder.checkbox.setFocusable(false);
				convertView.setTag(holder);
			}else{
				holder = (ViewHolder) convertView.getTag();
			}
			Log.i(tag, "Creating the list");
			holder.firstLine.setText(this.eventTitleArray[position]);
			holder.secondLine.setText(this.eventDateArray[position]);

			Bitmap bitmap;
			try {
				bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://eventur.sis.pitt.edu/images/heinz7.jpg").getContent());
			} catch (MalformedURLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				bitmap = BitmapFactory.decodeFile("assets/heinz7.jpg");//decodeFile(getResources().getAssets().open("icon.png"));
				e1.printStackTrace();
			}
			try {
				try{
					bitmap = BitmapFactory.decodeStream((InputStream)new URL(this.eventImageLinkArray[position]).getContent());}
				catch(Exception e){
					bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://eventur.sis.pitt.edu/images/heinz7.jpg").getContent());
				}

				int width = 0;
				int height =0;
				int newWidth = 50;
				int newHeight = 40;

				try{
					width = bitmap.getWidth();
					height = bitmap.getHeight();
				}
				catch(Exception e){
					width = 50;
					height = 40;
				}
				float scaleWidth = ((float)newWidth)/width;
				float scaleHeight = ((float)newHeight)/height;
				Matrix mat = new Matrix();
				mat.postScale(scaleWidth, scaleHeight);

				try{
					Bitmap newBitmap = Bitmap.createBitmap(bitmap,0,0,width,height,mat,true);
					BitmapDrawable bmd = new BitmapDrawable(newBitmap);
					holder.imageView.setImageDrawable(bmd);
					holder.imageView.setScaleType(ScaleType.CENTER);
				}
				catch(Exception e){

				}

			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}



			return convertView;
		}
		class ViewHolder{
			TextView firstLine;
			TextView secondLine;
			ImageView imageView;
			//CheckBox checkbox;

		}



	}

}